﻿using System.Collections.Generic;
using System.Linq;

namespace RedEye.CMA.CodeTest
{
	public sealed class PatternMatcher
	{
		private readonly char[] _initialText;

		public PatternMatcher(string source)
		{
			_initialText = source.ToLower().ToCharArray();
		}

		public int[] Match(string subText)
		{
			subText = subText.ToLower();
			return new List<int>(FindMatchesYieldPosition(0, subText)).ToArray();
		}

		private IEnumerable<int> FindMatchesYieldPosition(int startIndex, string subText)
		{
			if (startIndex == _initialText.Length - 1)
				yield break;

			int nextPossibleStart = FindNextPossibleStartPosition(startIndex, subText.First());
			if (nextPossibleStart == -1)
				yield break;


			if (IsAMatch(nextPossibleStart, subText))
			{
				yield return ++nextPossibleStart;
			}
			foreach (int index in FindMatchesYieldPosition(nextPossibleStart + subText.Length, subText))
			{
				yield return index;
			}
		}

		private bool IsAMatch(int startIndex, string subtext)
		{
			int pointer = startIndex;
			foreach (char c in subtext)
			{
				for (int i = pointer; i < _initialText.Length; i++)
				{
					if (c == _initialText[i])
					{
						pointer++;
						break;
					}
					return false;
				}
			}
			return true;
		}

		private int FindNextPossibleStartPosition(int startIndex, char initialChar)
		{
			for (int i = startIndex; i < _initialText.Length; i++)
			{
				if (_initialText[i] == initialChar)
					return i;
			}
			return -1;
		}
	}
}